package com.my.demo.shiro.realms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.demo.pojo.User;
import com.my.demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

/**
 * @author liangyuanshao
 * @date 2021/12/22 - 11:48
 */
public class ShiroRealm  extends AuthorizingRealm {
  @Autowired
  UserService userService;

  @Override
  public boolean supports(AuthenticationToken token) {
    return token instanceof UsernamePasswordToken;
  }

  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    return null;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {

    System.out.println(token.getPrincipal());
    // 从 JwtToken 中获取当前用户
    String userName = (String) token.getPrincipal();

    //假设是从数据库获得的 用户名，密码
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("user_name", userName);
    User user=userService.getOne(wrapper);

    if(!ObjectUtils.isEmpty(user)){
      //返回数据库信息
      SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(),
          ByteSource.Util.bytes(user.getSalt()), this.getName());
      return simpleAuthenticationInfo;
    }

    return null;





  }

}
